import router, { constantRoutes } from '@/router';
import ParentView from '@/components/ParentView/index.vue';
import { RouterRecord } from "@/global/record/RouterRecord";

// 匹配views里面所有的.vue文件
const modules = import.meta.glob('./../../views/**/*.vue')

export const usePermissionStore = defineStore(
    'permission',
    () => {
      const routes = ref<RouterRecord[]>([]);

      const addRoutes = ref<RouterRecord[]>([]);

      const defaultRoutes = ref<RouterRecord[]>([]);

      const topbarRouters = ref<RouterRecord[]>([]);

      const sidebarRouters = ref<RouterRecord[]>([]);

      const sidebarBasePath = ref('');

      function setRoutes(routeList: RouterRecord[]) {
        addRoutes.value = routeList;
        routes.value = constantRoutes.concat(routeList);
      }

      function setDefaultRoutes(routeList: RouterRecord[]) {
        defaultRoutes.value = constantRoutes.concat(routeList)
      }

      function setTopbarRoutes(routeList: RouterRecord[]) {
        topbarRouters.value = routeList
      }

      function setSidebarRouters(routeList: RouterRecord[]) {
        sidebarRouters.value = routeList
      }

      function setSidebarBasePath(basePath: string) {
        sidebarBasePath.value = basePath;
      }

      function generateRoutes() {
        // 向后端请求路由数据
        return getRoutersApi().then(res => {
          const sdata: RouterRecord[] = JSON.parse(JSON.stringify(res.data))

          const rdata: RouterRecord[] = JSON.parse(JSON.stringify(res.data))

          const sidebarRoutes = filterAsyncRouter(sdata)

          const rewriteRoutes = filterAsyncRouter(rdata, false, true)

          setRoutes(rewriteRoutes)
          setSidebarRouters(constantRoutes.concat(sidebarRoutes))
          setDefaultRoutes(sidebarRoutes)
          setTopbarRoutes(sidebarRoutes)
          return rewriteRoutes
        })
      }

      return {
        routes,
        addRoutes,
        defaultRoutes,
        topbarRouters,
        sidebarRouters,
        setRoutes,
        setDefaultRoutes,
        setTopbarRoutes,
        setSidebarRouters,
        sidebarBasePath,
        setSidebarBasePath,
        generateRoutes,
      }
    }
)

// 遍历后台传来的路由字符串，转换为组件对象
function filterAsyncRouter(asyncRouterMap: RouterRecord[], lastRouter: RouterRecord | boolean = false, type = false) {
  return asyncRouterMap.filter(route => {
    if (type && route.children) {
      route.children = filterChildren(route.children)
    }

    if (route.hidden) {
      const pathFirst = route.path.split('/').shift()
      if (pathFirst && route.component.includes(pathFirst)) {
        const compFirst = route.component.split(pathFirst).shift()
        if (compFirst) {
          route.meta['activeMenu'] = '/' + compFirst + pathFirst;
        }
      }
    }

    if (route.component) {
      if (route.component === 'Layout') {
        route.component = ParentView
      } else if (route.component === 'ParentView') {
        route.component = ParentView
      } else {
        route.component = loadView(route.component)
      }
    }
    if (route.children != null && route.children && route.children.length) {
      route.children = filterAsyncRouter(route.children, route, type)
    } else {
      delete route['children']
      delete route['redirect']
    }
    return true
  })
}

function filterChildren(childrenMap, lastRouter: any = false) {
  var children = []
  childrenMap.forEach((el, index) => {
    if (el.children && el.children.length) {
      if (el.component === 'ParentView' && !lastRouter) {
        el.children.forEach(c => {
          c.path = el.path + '/' + c.path
          if (c.children && c.children.length) {
            children = children.concat(filterChildren(c.children, c))
            return
          }
          children.push(c)
        })
        return
      }
    }
    if (lastRouter) {
      el.path = lastRouter.path + '/' + el.path
      if (el.children && el.children.length) {
        children = children.concat(filterChildren(el.children, el))
        return
      }
    }
    children = children.concat(el)
  })
  return children
}

export const loadView = (view) => {
  let res;
  for (const path in modules) {
    const dir = path.split('views/')[1].split('.vue')[0];
    if (dir === view) {
      res = () => modules[path]();
    }
  }
  return res;
}
